package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;

import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.UploadPicBaseActivity;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.dialog.MessageDialog;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.location.LocationUtils;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.DateTimePickDialogUtil;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.view.TextItemView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/2 0002.
 */
public class OnlineComplaintDetailActivity extends UploadPicBaseActivity {

    private static final int REFRESH_LIST = 101;
    private static final int REQUEST_CODE = 201;

    /*姓名,事发时间,事发区域,详细地址*/
    private TextItemView mTivTitle;
    private TextItemView mTivDate;
    private TextItemView mTivArea;
    private TextItemView mTivDetailAddress;

    /*投诉内容*/
    private EditText mEtContent;
    private String location;


    /*提交的按钮*/
    private Button mBtnSubmit;

    private ScrollView mScrollViewContent;
    private MessageDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_complaint_detail);

        setHeader();

        initView();

        initData();

        setListener();
    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.online_complaint);
        setLeftBtnVisibility(View.VISIBLE);
        setNextRightBtnVisibility(View.VISIBLE);
        setNextRightBtnBackground(R.drawable.online_my_complaint);
    }

    /**
     * 初始化控件
     */
    @Override
    public void initView() {
        super.initView();
        //标题
        mTivTitle = (TextItemView) findViewById(R.id.tiv_online_title);
        //事发时间
        mTivDate = (TextItemView) findViewById(R.id.tiv_online_date);
        //事发区域
        mTivArea = (TextItemView) findViewById(R.id.tiv_online_area);
        //详细地址
        mTivDetailAddress = (TextItemView) findViewById(R.id.tiv_online_detail_address);
        //投诉内容
        mEtContent = (EditText) findViewById(R.id.et_online_content);

        //提交按钮
        mBtnSubmit = (Button) findViewById(R.id.btn_online_complaint_submit);
        mScrollViewContent = (ScrollView) findViewById(R.id.sv_online_complaint);

        //默认时间为当天
        String dateInput = dateToStrLong();
        mTivDate.setText(dateInput);

        //TODO 区域默认仁和区
        mTivArea.setText(R.string.area_des);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //取得定位地址
        LocationUtils.getInstance(OnlineComplaintDetailActivity.this).startLocation(new LocationUtils.OnLocationListener() {
            @Override
            public void onLocationSuccess(String coor, String addr) {
                location = addr;
            }
        }, true);
    }

    /**
     * 设置监听
     */
    private void setListener() {

        mScrollViewContent.setOnClickListener(new MyClickListener());

        //点击我的投诉跳转到投诉处理界面
        setNextRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_OK, new Intent().putExtra(Constants.ONLINE_COMPLAINT_FLAG_NAME, Constants.ONLINE_COMPLAINT_FLAG));
                finish();
            }
        });

        //提交按钮的点击事件
        mBtnSubmit.setOnClickListener(new MyClickListener());

        //时间的点击时间
        mTivDate.setOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //展示日期的dialog
                if (dialog == null || !dialog.isShowing()) {
                    showTimerDialog();
                }
            }
        });

        //TODO 区域的点击,选择区域
//        mTivArea.setOnclickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //跳转到区域选择的界面
//                Intent intent = new Intent(OnlineComplaintDetailActivity.this , SelectAreaActivity.class) ;
//                intent.putExtra(Constants.SELECT_AREA , mTivArea.getText()) ;
//                startActivityForResult(intent, REQUEST_CODE);
//            }
//        });

    }


    /**
     * 展示日期的dialog
     */
    private void showTimerDialog() {

//        //获取当前的时间
        String inputDate = mTivDate.getText();

        DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(OnlineComplaintDetailActivity.this, inputDate);
        dialog = dateTimePicKDialog.dateTimePicKDialog(mTivDate, OnlineComplaintDetailActivity.this);
    }

    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd
     */
    public static String dateToStrLong() {
        Date date = new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置显示格式
        String nowTime = "";
        nowTime = dateFormat.format(date);
        return nowTime;
    }


    /**
     * 点击事件的监听
     */
    private class MyClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {

                case R.id.btn_online_complaint_submit:

                    //获取输入的内容
                    String title = mTivTitle.getText();
                    String date = mTivDate.getText();
                    String area = mTivArea.getText();
                    String detailAddress = mTivDetailAddress.getText();
                    String complaintContent = mEtContent.getText().toString().trim();

                    if (Tools.isEmpty(title)) {
                        MyToast.show(OnlineComplaintDetailActivity.this, "请输入投诉标题");
                        return;
                    }

                    if (Tools.isEmpty(date)) {
                        MyToast.show(OnlineComplaintDetailActivity.this, "请输入事发时间");
                        return;
                    }

                    if (Tools.isEmpty(area)) {
                        MyToast.show(OnlineComplaintDetailActivity.this, "请输入事发区域");
                        return;
                    }

                    if (Tools.isEmpty(detailAddress)) {
                        MyToast.show(OnlineComplaintDetailActivity.this, "请输入详细地址");
                        return;
                    }

                    if (Tools.isEmpty(complaintContent)) {
                        MyToast.show(OnlineComplaintDetailActivity.this, "请输入投诉内容");
                        return;
                    }

                    //上传数据

                    //替换文本中的换行符和回车键
                    String resultContent = Tools.replaceNewLine(complaintContent);

                    uploadData(title, date, area, detailAddress, resultContent);
                    break;

                case R.id.sv_online_complaint:
                    //隐藏软键盘
                    CommonUtils.hideSoftKeyboard(OnlineComplaintDetailActivity.this);
                    break;
            }
        }
    }

    /**
     * 上传数据
     *
     * @param title            标题
     * @param date             事发时间
     * @param area             事发区域
     * @param detailAddress    详细地址
     * @param complaintContent 投诉内容
     */
    private void uploadData(final String title, final String date, final String area, final String detailAddress, final String complaintContent) {

            uploadFile(new OnUploadCallback() {
                @Override
                public void onUploadSuccess() {

//                    DialogFactory.dismissLoadingDialog(loadingDialog);

                    //上传文字内容，及图片的URL
                    Map<String, Object> infos = new HashMap<>();
                    infos.put("title", title);
                    infos.put("operationtime", date);
                    infos.put("area", area);
                    infos.put("content", complaintContent);
                    infos.put("address", detailAddress);
                    infos.put("position", location);
                    infos.put("userid", CacheUtils.getIntData(OnlineComplaintDetailActivity.this, Constants.LOGIN_UID, 0));
                    infos.put("picurls", getUploadFileUrls());
                    infos.put("type", 2);//2代表工单
                    infos.put("videourl" , videoUrl == null ? "" : videoUrl) ;
                    infos.put("audiourl" , audioUrl == null ? "" : audioUrl) ;
                    DialogFactory.showDialog(loadingDialog);
                    MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.POST_ADD_COMPLAIN_URL, infos, MyHttp.POST, OnlineComplaintDetailActivity.this,
                            false, null,
                            new SimplePaserJsonCallback() {

                                @Override
                                public void onVerifySuccess(String dataRaw, boolean isCache) {
                                }

                                @Override
                                public void onVerifyIsNull() {
                                    if (!isFinishing()) {
                                        uploadfileUrls.clear();//清除url
                                        DialogFactory.dismissLoadingDialog(loadingDialog);
                                        MyToast.show(OnlineComplaintDetailActivity.this, "提交成功！");
                                        setResult(RESULT_OK, new Intent().putExtra(Constants.ONLINE_COMPLAINT_FLAG_NAME, Constants.ONLINE_COMPLAINT_FLAG));
                                        finish();
                                    }
                                }

                            }, new HttpFailCallback() {
                                @Override
                                public void onServiceErrorCallback() {
                                    DialogFactory.dismissLoadingDialog(loadingDialog);
                                }
                            });

                }
            });

    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
      switch (msg.what) {
            case REFRESH_LIST:
                break;
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }


    @Override
    protected void onStop() {
        super.onStop();
        LocationUtils.getInstance(OnlineComplaintDetailActivity.this).stopLocation();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == REQUEST_CODE){
            if (resultCode == RESULT_OK){
                String selectArea = intent.getStringExtra(Constants.SELECT_AREA);
                String inputArea = mTivArea.getText();
                if (!inputArea.equals(selectArea)){
                    mTivArea.setText(selectArea);
                }
            }
        }
    }
}
